//回到顶部
function backToTop() {
    const toTop = document.querySelector('.backTop>img');
    toTop.addEventListener('click', () => {
        let Timer = setInterval(function () {
            document.documentElement.scrollTop -= 50
            if (document.documentElement.scrollTop < 50) {
                document.documentElement.scrollTop = 0
                clearInterval(Timer)
            }
            if (document.documentElement.scrollTop == 0) {
                clearInterval(Timer)
            }
        }, 20)

    })
}
backToTop()

/*
   显示用户信息
*/
function showUser() {
    let user = localStorage.getItem('USER')
    user = JSON.parse(user)
   //  console.log(user);
   //  console.log(user.username);
    let headerStr = `
                     <img src="${user.headerimg}" alt="">
                     <p>用户名: ${user.username}</p>
                     <p>年龄：${user.age}</p><br>
                     <button>退出</button>`

   const title = document.querySelector('header>.title')
   title.innerHTML = headerStr
}
showUser()
/**
* 退出
*   1. 清除localStorage登录用户信息
*/
function logout() {
   const logoutBtn = document.querySelector('.title>button')
   logoutBtn.addEventListener('click', function () {
       // 1. 清除localStorage登录用户信息
       localStorage.removeItem('USER')
       // 2. 跳转到登录界面
       location.href = './login.html'
   })
}
logout()
const tableEle = document.querySelector('table')
let cartListStr = localStorage.getItem('DS-CART-LIST')
let cartList = JSON.parse(cartListStr) || []
let stateAll = false

/**
 * 动态渲染购物车
 */
function showCartList() {
    let trStr = cartList.map(item => {
        return `<tr>
					<td><input type="checkbox" name="checksingle" ${item.state ? 'checked' : ''} data-index="${item.id}"></td>
                    <td><img src="${item.url}" alt="p2" /></td>
                    <td>${item.name}</td>
                    <td>￥${item.price}</td>
                    <td>
                        <input type="button" value="-" name="minus" data-index="${item.id}" ${item.num == 0 ? 'disabled' : '0'} />
                        <input type="text" value="${item.num}" name="amount" />
                        <input type="button" value="+" name="plus" data-index="${item.id}"/>
                    </td>
                    <td class="all-price">￥${(item.num * item.price).toFixed(2)}</td>
                    <td>
                        <a href="#">移入收藏</a><br />
                        <a href="#" class="del" data-index="${item.id}">删除</a>
                    </td>
                </tr>`
    }).join('')

    let thStr = `<tr>
                <th><input type="checkbox" name="checkall" ${stateAll ? 'checked' : ''}>全选</th>
                <th>商品图片</th>
                <th width="300px">商品信息</th>
                <th>单价</th>
                <th>数量</th>
                <th width="100px">总价</th>
                <th>操作</th>
            </tr>`
    thStr += trStr

    tableEle.innerHTML = thStr

}

/*
   操作商品
 */
function onProduct() {
    /*
         删除
    */
    tableEle.addEventListener('click', function (e) {
        e = e || window.event
        let target = e.target || e.srcElement
        if (target.getAttribute('class') == 'del') {
            let id = target.getAttribute('data-index')
            console.log('>>>' + id);
            // console.log('cartList' + cartList);
            let index = cartList.findIndex(item => item.id == id)
            cartList.splice(index, 1)
            showCartList()
            onTotalPrice()
        }

        /*
             加一
        */
        if (target.getAttribute('value') == '+') {
            let id = target.getAttribute('data-index')
            let product = cartList.find(item => item.id == id)
            // console.log('product'+product);
            product.num++
            product.singlePrice = (product.num * product.price).toFixed(2)
            showCartList()
            onTotalPrice()

        }
        /**
         * 减操作
         */
        if (target.getAttribute('value') == '-') {
            //获取id
            let id = target.getAttribute('data-index')
            //查找商品
            let product = cartList.find(item => item.id == id)

            //数量减一
            product.num--
            if (product.num < 0) {
                product.num = 0
            }
            //计算价格
            product.singlePrice = (product.num * product.price).toFixed(2)
            showCartList()
            onTotalPrice()
        }

        /*
             全选功能
        */
        if (target.getAttribute('name') == 'checkall') {
            stateAll = !stateAll
            cartList.forEach(item => (item.state = stateAll))

            onTotalPrice()
            showCartList()

        }

        /*
            单选功能
         */
        if (target.getAttribute('name') == 'checksingle') {
            let id = target.getAttribute('data-index')
            let product = cartList.find(item => item.id == id)
            product.state = !product.state
            product.singlePrice = (product.num * product.price).toFixed(2)
            let sum = Number(product.singlePrice)
            if (product.state == true) {
                onTotalPrice()
            } else {
                product.singlePrice = -(product.num * product.price).toFixed(2)
                onTotalPrice()

            }
            stateAll = cartList.every(item => item.state == true)
            showCartList()
        }
    })
}
const totalPriceEle = document.querySelector('.total-price>span')

function onTotalPrice() {
    let sum = 0
    for (let i = 0; i < cartList.length; i++) {
        if (cartList[i].state == true) {
            console.log('cartList: ' + cartList[i]);
            let singlePrice = (cartList[i].num*cartList[i].price).toFixed(2)
            // let singlePrice = cartList[i].singlePrice
            console.log('>>' + singlePrice);
            sum += Number(singlePrice)
        }
    }
    totalPriceEle.innerHTML = `￥${sum.toFixed(2)}`
}


function addProduct() {
    const form = document.querySelector('form')
    const nameEle = document.querySelector('input[name="name"]')
    const priceEle = document.querySelector('input[name="price"]')
    const numEle = document.querySelector('input[name="num"]')
    const urlEle = document.querySelector('input[name="url"]')

    form.addEventListener('submit', function (e) {
		e = e || window.event 
		e.preventDefault() 

		let id = getRandom(1000, 10000)
		let name = nameEle.value 
		let price = priceEle.value
		let num = numEle.value 
		let url = urlEle.value 

		let product = {
			id,
			name,
			url,
			price,
			num,
			singlePrice: 0,
			state: false, 
		}
		cartList.push(product)

		showCartList()

		nameEle.value = ''
		priceEle.value = ''
		numEle.value = ''
		urlEle.value = ''
	})
}
addProduct()
/*
     获取m-n之间的随机数
*/
function getRandom(m, n) {
    var max = Math.max(m, n)
    var min = Math.min(m, n)
    return Math.floor(Math.random() * (max - min) + min)
}
showCartList()
onProduct()
onTotalPrice()